package com.ai.chat.service.impl;

import com.ai.chat.entity.User;
import com.ai.chat.mapper.UserMapper;
import com.ai.chat.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User login(String username, String password) {
        // 查询用户
        User user = userMapper.selectByUsername(username);
        Assert.notNull(user, "用户名或密码错误");
        Assert.isTrue(user.getIsDeleted() == 0, "用户已被禁用");

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new IllegalArgumentException("用户名或密码错误");
        }

        // 返回用户信息（不含密码）
        user.setPassword(null);
        return user;
    }

    @Override
    public Long register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        Assert.isNull(existingUser, "用户名已存在");

        // 设置默认值
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setIsDeleted(0);

        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 保存用户
        userMapper.insert(user);
        return user.getId();
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        Assert.notNull(user, "用户不存在");
        Assert.isTrue(user.getIsDeleted() == 0, "用户已被禁用");
        user.setPassword(null);
        return user;
    }
}